package http;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2016/7/23.
 */
public class DefineSocketTest {
    public static class EchoHandlerThread implements Runnable
    {
        private final Socket sock;
        private final int id;

        public EchoHandlerThread(Socket s, int i)
        {
            sock = s;
            id = i;
        }

        public void run()
        {
            try {
                //----- set socket read timeout to 10 seconds -----
                sock.setSoTimeout(5000);

                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);


                BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));

                String input;
                while ((input = in.readLine()) != null) {
                    System.out.println("[" + id + "] <" + input + ">");
                }

                out.close();
                in.close();
                sock.close();

                System.out.println("\tConnection #" + id + " closed");
            }
            catch (Exception ex) {
                //throw new RuntimeException(ex);
                try {
                    sock.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            finally{

            }

        }
    }

    public static class Listener
    {
        private final InetAddress bindip;
        private final int portnum;

        public Listener(String ipstr, int pn)
        {
            try {
                bindip = InetAddress.getByName(ipstr);
                portnum = pn;
            }
            catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

        public void start()
        {
            try {
                ServerSocket srvsock = new ServerSocket(portnum, 100, bindip);
                System.out.println("Listening on " + bindip.getHostAddress() + ":" + portnum);

                int connum = 0;
                while (true) {
                    Socket sock = srvsock.accept();

                    connum++;
                    InetAddress ipaddr = sock.getInetAddress();
                    System.out.println("Connection #" + connum + " from: " + ipaddr.getHostAddress());

                    new Thread(new EchoHandlerThread(sock, connum)).start();
                }
            }
            catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }


    public static void main(String[] args)
    {
        Listener lsnr = new Listener("localhost", 8192);
        lsnr.start();
    }
}
